package run.iget.tools.core;

import java.util.Stack;

/**
 * Copyright (C), 2021，行动改变认知[iget.run]
 * 代码千万行，注释第一行
 * ---------------类的作用描述---------------
 * 数字工具类
 * ---------------类的作用描述---------------
 *
 * @author 大周|450513554@qq.com
 * @since 2021/3/29 11:16:30
 */
public class NumberUtils {

    /**
     * 0-9编码
     */
    private static final String CODE_TABLE_0_9 = "0123456789";
    /**
     * A-Z编码
     */
    private static final String CODE_TABLE_A_Z = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    /**
     * a-z编码
     */
    private static final String CODE_TABLE_a_z = "abcdefghijklmnopqrstuvwxyz";

    /**
     * 62位编码字符数组
     */
    private static final char[] CHAR_62_ARRAY = (CODE_TABLE_0_9 + CODE_TABLE_A_Z + CODE_TABLE_a_z).toCharArray();

    /**
     * 功能描述: 将10进制转化为62进制
     * @param number -- 要转换的10进制数值，不可<0, 否则会抛异常
     * @return 62进制的字符串
     * @throws IllegalArgumentException
     */
    public static String encode10To62(long number){
        return encode10To62(number, 0);
    }

    /**
     * 将10进制转化为62进制
     * @param number -- 要转换的10进制数值，不可<0, 否则会抛异常
     * @param length -- 转化成的62进制长度，不足length长度的话高位补0，否则不改变什么
     * @return 62进制的字符串
     * @throws IllegalArgumentException
     */
    public static String encode10To62(long number, int length){
        if (number < 0) {
            throw new IllegalArgumentException("number必须>=0");
        }
        StringBuilder result = new StringBuilder(0);
        Long rest = number;
        Stack<Character> stack = new Stack<Character>();
        while(rest != 0){
            stack.add(CHAR_62_ARRAY[new Long((rest - (rest / CHAR_62_ARRAY.length) * CHAR_62_ARRAY.length)).intValue()]);
            rest = rest / CHAR_62_ARRAY.length;
        }
        if (number == 0) {
            stack.add(CHAR_62_ARRAY[0]);
        }
        for(;!stack.isEmpty();){
            result.append(stack.pop());
        }
        if (length > 0) {
            StringBuilder returnStr = new StringBuilder();
            for(int i = 0; i < length - result.length(); i++){
                returnStr.append('0');
            }
            returnStr.append(result.toString());
            return returnStr.toString();
        }
        return result.toString();
    }

    /**
     * 将62进制转换成10进制数
     * @param ident62 -- 被encode10To62编码的62进制字符串
     * @return 10进制数值
     */
    public static long decode62To10(String ident62) {
        long dst = 0L;
        for(int i=0; i<ident62.length(); i++) {
            char c = ident62.charAt(i);
            for(int j=0; j<CHAR_62_ARRAY.length; j++) {
                if(c == CHAR_62_ARRAY[j]) {
                    dst = (dst * CHAR_62_ARRAY.length) + j;
                    break;
                }
            }
        }
        return dst;
    }


}
